import React, { useEffect, useMemo, useState, useRef } from "react";
import ajax from "@/services";
import { echartTypes } from "@/config/character";
import { FormSelect, ResultWrap } from "@/components";
import { SketchPicker } from 'react-color'
import { message } from "antd";
import sheng_polygon from "./data/sheng_polygon.json"; // 省份地图数据
import shi_polygon from "./data/shi_polygon.json"; // 省份地图数据


/**
 * 线性插值函数，用于在两个颜色之间计算中间色
 * @param {string} color1 - 第一个颜色（十六进制）
 * @param {string} color2 - 第二个颜色（十六进制）
 * @param {number} t - 插值参数，范围从0到1
 * @return {string} 插值后的颜色（十六进制）
 */
function lerpColor(color1, color2, t) {
  // 将十六进制颜色转换为RGB
  const rgb1 = parseInt(color1.slice(1), 16);
  const r1 = (rgb1 >> 16) & 0xff;
  const g1 = (rgb1 >> 8) & 0xff;
  const b1 = rgb1 & 0xff;

  const rgb2 = parseInt(color2.slice(1), 16);
  const r2 = (rgb2 >> 16) & 0xff;
  const g2 = (rgb2 >> 8) & 0xff;
  const b2 = rgb2 & 0xff;

  // 计算插值后的RGB值
  const r = Math.round(r1 + (r2 - r1) * t);
  const g = Math.round(g1 + (g2 - g1) * t);
  const b = Math.round(b1 + (b2 - b1) * t);

  // 将RGB值转换回十六进制颜色
  return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, '0')}`;
}

/**
 * 线性插值函数，用于在两个颜色之间计算中间色
 * @param {string} color1 - 第一个颜色（十六进制）
 * @param {string} color2 - 第二个颜色（十六进制）
 * @param {number} t - 插值参数，范围从0到1
 * @return {string} 插值后的颜色（十六进制）
 */
function interpolateColor(color1, color2, t) {
  const [r1, g1, b1] = parseInt(color1.slice(1), 16).toString(16).match(/.{2}/g).map(hex => parseInt(hex, 16));
  const [r2, g2, b2] = parseInt(color2.slice(1), 16).toString(16).match(/.{2}/g).map(hex => parseInt(hex, 16));

  const r = Math.round(r1 + (r2 - r1) * t);
  const g = Math.round(g1 + (g2 - g1) * t);
  const b = Math.round(b1 + (b2 - b1) * t);

  return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
}

/**
 * 根据值返回对应的色号
 * @param {number} value - 输入的值
 * @param {number} minValue - 数据的最小值
 * @param {number} maxValue - 数据的最大值
 * @param {Array} colorScale - 颜色数组，包含色号
 * @return {string} 返回对应的色号
 */
function getColorForValue(value, minValue, maxValue, colorScale) {
  // 计算值在最小值和最大值之间的比例
  const ratio = (value - minValue) / (maxValue - minValue);

  // 计算颜色数组中的位置
  const colorIndex = Math.min(Math.floor(ratio * (colorScale.length - 1)), colorScale.length - 1);

  // 如果是数组的第一个或最后一个颜色，直接返回
  if (colorIndex === 0 || ratio === 1) {
    return colorScale[colorIndex];
  }

  // 计算两个颜色之间的插值
  const t = (ratio * (colorScale.length - 1)) - colorIndex;
  return interpolateColor(colorScale[colorIndex], colorScale[colorIndex + 1], t);
}

// 预置色带颜色数组
// const colorScale = [
//   "#1F196D", // 暗紫色
//   "#31369e",  // 淡紫色
//   "#005EFF", // 蓝色
//   "#1E90A8",  // 青色
//   "#00B457",  // 绿色
//   "#28E156",  // 黄绿色
//   "#B7FF01",  // 黄色
//   "#FFC800",  // 橙色
//   "#FF610C",  // 红色
//   "#D13438"   // 暗红色
// ];

// // 示例使用
// const minValue = 0; // 数据的最小值
// const maxValue = 10; // 数据的最大值
// const value = 7; // 输入的值

// const color = getColorForValue(value, minValue, maxValue, colorScale);
// console.log(color); // 输出对应的色号

let map = null;
var geojsonLayer = null;
// var chart_type = "地图热力图";
export default function Heatmap(props) {
  const { type = "5" } = props;

  const [loading, setLoading] = useState(true);
  // 全部柱状图数据
  const [data, setData] = useState([]); // 下拉地图数据
  const [currentData, setCurrentData] = useState({});
  const mapRef = useRef(null);

  const [defaultColors, setDefaultColors] = useState([
    {id:'默认1', name:'色带1', data:["#FFC800", "#FFC800", "#FF610C",  "#D13438"]},
    {id:'默认2', name:'色带2', data:['#e9e8c9', '#a8be98','#6aa2c1', '#586a9f', '#1e2b5a' ]},
    {id:'默认3', name:'色带3', data:['#cccccc', '#aaaaaa', '#888888', '#333333']},
    {id:'默认4', name:'色带4', data:['#213660', '#394e61', '#445e79', '#506e9d', '#85a0bd', '#dae5eb', '#f9f7f2', '#faebe2','#d8b599', '#d0ac98',  '#c16e5c', '#7a3238', '#542029']}
  ])

  const [currentColor, setCurrentColor] = useState(
    {id:'默认1', name:'色带1', data:["#FFC800", "#FFC800", "#FF610C",  "#D13438"]}
  )

  const getData = () => {
    // setLoading(true);
    let chart_type = echartTypes.filter((item) => item.value === type)[0]?.label || "";

    ajax
      .getFileList({ chart_type, }, false)
      .then(
        (res) => {
          const heatmapData = res.data.filter(d => d.chart_type === chart_type && (d.file_name.indexOf('省') !== -1 || d.file_name.indexOf('市') !== -1 ))
          let findItem = heatmapData.filter((item) => item.is_default == 1)[0] || data[0];
          setCurrentData(findItem);
          
          setData(heatmapData);
        },
        (err) => {
          setData([]);
        }
      )
      .finally(() => {
        // setLoading(false);
      });
  };

  useEffect(() => {
    map = L.map(mapRef.current, {
      crs: L.CRS.EPSG4326,
      center: [38.76921186940223, 104.96006026204887],
      zoom: 2
    });
    window.pmap = map;
    var activeDraw = false; // 全局参数,是否正在画线
    const VEC_C = 'http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
    const CVA_C = 'http://t1.tianditu.com/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
    const keys = ['0db778f3a181108e2cbb155d495fc774', 'bc7199b502d057ad5be9712329bcdbad'];
    const TK_KEY = keys[parseInt((Math.random() * keys.length))]; 
    L.tileLayer(VEC_C + TK_KEY, {
      maxZoom: 20,
      tileSize: 256,
      zoomOffset: 1,
    }).addTo(map);
    L.tileLayer(CVA_C + TK_KEY, {
      maxZoom: 20,
      tileSize: 256,
      zoomOffset: 1,
    }).addTo(map);

    map.whenReady(()=>{
      getData();
    })

    return () => {
      map && map.remove();
    }
  }, [])


  // 更新地图
  useEffect(() => {
    console.log('currentData', currentData);
    if (Object.getOwnPropertyNames(currentData).length === 0) return;

    let features = [];
    let min_Value = parseFloat(currentData.data[0].value) 
    let max_Value = parseFloat(currentData.data[0].value)
    if ( currentData.file_name.split('.')[0].endsWith('省') ) {
      // 省级地图

      sheng_polygon.features.forEach(fea => {
        let item = currentData.data.find(it => { 
          return it.name === fea.properties.name || fea.properties.name.includes(it.name) || it.name.includes(fea.properties.name)
        })
        if (item) {
          min_Value = Math.min(min_Value, item.value)
          max_Value = Math.max(max_Value, item.value)
        }
        features.push({
          ...fea,
          properties: {
            ...fea.properties,
            value: item?.value || null
          }
        })
      })
    } else if ( currentData.file_name.split('.')[0].endsWith('市') ) {
      // 市级地图
      shi_polygon.features.forEach(fea => {
        let item = currentData.data.find(it => { 
          return it.name === fea.properties.NAME || fea.properties.NAME.includes(it.name) || it.name.includes(fea.properties.NAME)
        })
        if (item) {
          min_Value = Math.min(min_Value, item.value)
          max_Value = Math.max(max_Value, item.value)
        }
        features.push({
          ...fea,
          properties: {
            ...fea.properties,
            value: item?.value || null
          }
        })
      })
    } else {
      message.error('暂不支持该文件类型')
      return;
    }
    console.log(features);
    "#f15419","#d43735","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#ff610c","#fe600d","#f75a13","#f75a13","#FFC800","#d93c30","#d33636","#f65815","#e24528","#de412c","#d93c31","#d63933","#db3e2e","#fa5c10","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#f15419","#da3d2f","#ed4f1d","#fb5d10","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#f45716","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fe600d","#ed501d","#e64923","#dc3e2e","#d73a32","#D13438","#dc3e2e","#f1531a","#f35517","#d63933","#d93c30","#e44726","#de402c","#df412b","#e04329","#e84a22","#ee501c","#f65815","#f55716","#f95c11","#ee501c","#f85a13","#f1531a","#fc5e0f","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fc5e0f","#FFC800","#f65914","#f45617","#f75914","#ff610c","#fc5e0f","#fc5e0f","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fd5f0e","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fd5f0e","#FFC800","#FFC800","#FFC800","#ff610c","#FFC800","#FFC800","#FFC800","#f55716","#FFC800","#fe600d","#fb5d10","#fd5f0e","#f75913","#ed4f1d","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fe600c","#FFC800","#FFC800","#FFC800","#FFC800","#f55716","#fc5e0f","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800","#fc5e0f","#fa5c10","#fb5d10","#f85b12","#fc5e0e","#FFC800","#FFC800","#FFC800","#fe600d","#FFC800","#e64924","#e14429","#f35518","#da3c30","#FFC800","#FFC800","#FFC800","#FFC800","#FFC800"
    geojsonLayer && map.removeLayer(geojsonLayer)
    let mycolor = []
    geojsonLayer = L.geoJSON({type: "FeatureCollection", features: features}, {
      style: function (feature) {
        // if (feature.properties.value) {
        //   mycolor.push(getColorForValue(feature.properties.value, minValue, maxValue, currentColor.data))
        //   // console.log(feature.properties.value, minValue, maxValue, currentColor.data, getColorForValue(feature.properties.value, minValue, maxValue, currentColor.data))
        // }
        return {
          fillColor: feature.properties.value ?  getColorForValue(feature.properties.value, min_Value, max_Value, currentColor.data): '#bbb',
          fillOpacity: 1,
          weight: 0.4,
          opacity: 0.8,
          color: 'rgb(128, 128, 128)',
        };
      },
    }).bindPopup(function (layer) {
      return `<div>
            <div><b>地区：</b>${layer.feature.properties.name || layer.feature.properties.NAME || '-'}</div>
            <div><b>值：</b>${layer.feature.properties.value || '-'}</div>
        </div>`;
    }).addTo(map);

    console.log(JSON.stringify(mycolor))
    // map.removeLayer(geojsonLayer)
    // geojsonLayer.setData();
    // 缩放到当前
    var enveloped = turf.envelope(turf.featureCollection(features));
    console.log(enveloped, geojsonLayer);
    map.fitBounds([[enveloped.bbox[1], enveloped.bbox[0]],[enveloped.bbox[3], enveloped.bbox[2]]])

  }, [currentData, currentColor])

  return (
    <div className="echart-com-container" style={{ padding: "10px" }}>
      <div className="title-header">
        {/* <a className="file-name" target="_blank" href={currentData.file_path} download>
          {currentData.file_name || "-"}
        </a> */}
        <FormSelect
          className="select-box"
          placeholder="切换文件"
          options={data}
          allowClear={false}
          value={currentData.id}
          onChange={(v) => {
            const findItem = data.find((item) => item.id === v);
            setCurrentData(findItem);
          }}
          style={{ width: 150 }}
          fieldNames={{ value: "id", label: "file_name" }}
        />
        
        <FormSelect
          className="select-box"
          placeholder="切换色带"
          options={defaultColors}
          allowClear={false}
          value={currentColor.id}
          onChange={(v) => {
            console.log(v)
            const item = defaultColors.find(c => c.id === v);
            setCurrentColor({ ...item });
          }}
          style={{ width: 100 }}
          fieldNames={{ value: "id", label: "name" }}
        />
         {/* <SketchPicker
            color={currentColor.data[1]}
            onChangeComplete={ handleChangeComplete }
        />
        <SketchPicker
            value={currentColor.data[1]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          />
        <SketchPicker
            value={currentColor.data[2]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          />
        <SketchPicker
            value={currentColor.data[3]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          /> */}
      </div>
      <div className="echart-body">
        <ResultWrap >
          <div ref={mapRef} style={{ width: '100%', height: '100%' }}></div>
        </ResultWrap>
      </div>
    </div>
  );
}
